package edu.ncut.vod.jsf.examonline.selfmadevalidator;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.sun.faces.util.MessageFactory;

import edu.ncut.vod.jsf.examonline.managedbeans.AddStudentBean;

public class AddressValidator implements Validator {

    /**
     * validate field 'address':its length can not be longer than 20
     */
    public void validate(FacesContext context, UIComponent component, Object obj)
            throws ValidatorException {
        debug("method validate in class AddressValidator is called");

        String label = ((HtmlInputText) component).getLabel();

        if ("address".equals(label)) {
            String fieldValue = (String) obj; // get the value of field which needs validating

            // validate field 'address':its length can not be longer than 20
            if(fieldValue.length() > 20){
                FacesContext facesContext = FacesContext.getCurrentInstance();
                FacesMessage msg = MessageFactory.getMessage(facesContext,
                        "addressLenght_canNotBeLongerThan20",
                        "addressLenght_canNotBeLongerThan20");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("addStudent:address", msg);
                setErrorMessageVisible();
                throw new ValidatorException(msg);
            }else{
				setErrorMessageInvisible();
			}
        }
    }

    /**
     * set error message tag of tag 'h:inputText' visible
     */
    public void setErrorMessageVisible(){
        debug("method setErrorMessageVisible in class AddressValidator is called");

        FacesContext context =FacesContext.getCurrentInstance();
        Application application=context.getApplication();
        AddStudentBean addStudentBean=(AddStudentBean)application.evaluateExpressionGet(context,"#{addStudentBean}",AddStudentBean.class);

        addStudentBean.setAddressNotice(true);
        addStudentBean.setAddressMessage(true);
    }

    /**
	 * set error message tag of tag 'h:inputText' invisible
	 */
    public void setErrorMessageInvisible(){
		debug("method setErrorMessageInvisible in class AddressValidator is called");

		FacesContext context =FacesContext.getCurrentInstance();
        Application application=context.getApplication();
        AddStudentBean addStudentBean=(AddStudentBean)application.evaluateExpressionGet(context,"#{addStudentBean}",AddStudentBean.class);

        addStudentBean.setAddressNotice(false);
        addStudentBean.setAddressMessage(false);
	}

    /**
     * print message on console
     * @param message
     */
    public void debug(String message) {
        System.out.println(message);
    }
}
